const orderModel = appRequire('models/order');
const userModel = appRequire('models/user');
const wxConfig = appRequire('config');

var request = require('request');
var xmlreader = require("xmlreader");
var wxMiniPayUnits = appRequire('common/wx/wxMiniPayUnits');

//var wxurl = wxConfig.wxPay.noticeUrl//通知地址
var wxurl = "https://newartapi.jimuzhou.cloud/wx/wxVipNotice"//通知地址正式

module.exports = {
    getSession,
    wxPay,
    wxH5Pay
};


//微信支付
async function wxH5Pay(req, thisResponse) {
    //首先拿到前端传过来的参数
    let postData = req.body;
    let orderCode = postData.orderCode;
    let money = postData.money;
    let CODE = postData.code;

    let appid = "wx65a30b3ef4afe860"
    let appsecret = "1bd2ea37caa09e2c60bbb433bb5333b6"
    let mchid = "1600766491"
    let mchkey = "xrXR1234567891234567891234567891"

    let user = await userModel.user.findByPk(postData.uid)
    if (user.vipTime) {
        let returnData = {
            code: 0,
            msg: "已是会员，无需再次充值"
        }
        thisResponse.json(returnData)
    } else {
        let thisUser = await userModel.user.findOne({
            where: {
                objectId: postData.uid
            }
        })
        let openid = thisUser.wcMiniId
        //console.log('APP传过来的参数是', orderCode + '----' + money + '------'  + '----' + appid + '-----' + appsecret + '-----' + mchid + '-----' + mchkey);

        //首先生成签名sign
        // appid
        let mch_id = mchid;
        let nonce_str = wxMiniPayUnits.createNonceStr();
        let timestamp = wxMiniPayUnits.createTimeStamp();
        let body = '美术课件云助手-会员服务';
        let out_trade_no = orderCode;
        let total_fee = wxMiniPayUnits.getmoney(money);
        let spbill_create_ip = req.connection.remoteAddress; // 支持IPV4和IPV6两种格式的IP地址。调用微信支付API的机器IP
        let notify_url = wxurl;
        let trade_type = 'JSAPI';  // 'APP';公众号：'JSAPI'或'NATIVE'

        let sign = wxMiniPayUnits.paysignjsapi(appid, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, trade_type, mchkey);

        // console.log('sign==', sign);

        //组装xml数据
        var formData = "<xml>";
        formData += "<appid>" + appid + "</appid>";  //appid
        formData += "<body><![CDATA[" + "美术课件云助手-会员服务" + "]]></body>";
        formData += "<mch_id>" + mch_id + "</mch_id>";  //商户号
        formData += "<nonce_str>" + nonce_str + "</nonce_str>"; //随机字符串，不长于32位。
        formData += "<notify_url>" + notify_url + "</notify_url>";
        formData += "<openid>" + openid + "</openid>";
        formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>";
        formData += "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>";
        formData += "<total_fee>" + total_fee + "</total_fee>";
        formData += "<trade_type>" + trade_type + "</trade_type>";
        formData += "<sign>" + sign + "</sign>";
        formData += "</xml>";

        //console.log('formData===', formData);

        var url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

        request({ url: url, method: 'POST', body: formData }, function (err, response, body) {
            if (!err && response.statusCode == 200) {
                console.log(body);

                xmlreader.read(body.toString("utf-8"), async function (errors, response) {
                    if (null !== errors) {
                        console.log(errors)
                        return;
                    }
                    console.log('长度===', response.xml.prepay_id.text().length);
                    var prepay_id = response.xml.prepay_id.text();
                    console.log('解析后的prepay_id==', prepay_id);

                    //将预支付订单和其他信息一起签名后返回给前端
                    let package = "prepay_id=" + prepay_id;
                    let signType = "MD5";
                    let minisign = wxMiniPayUnits.paysignjsapimini(appid, nonce_str, package, signType, timestamp, mchkey);

                    //创建单据
                    await orderModel.order.create({
                        objectId: sid.uuid(),
                        out_trade_no: out_trade_no,
                        status: 0,
                        payMoney: Number(money),
                        storeMoney: (Number(money) * 0.8),
                        parent: postData.uid,
                        buyerId: postData.uid,
                        type: 2
                    })

                    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);
                    returnData.data = {
                        'appId': appid,
                        'partnerId': mchid,
                        'prepayId': prepay_id,
                        'nonceStr': nonce_str,
                        'timeStamp': timestamp,
                        'package': 'Sign=WXPay',
                        'paySign': minisign,
                    }
                    thisResponse.json(returnData);
                });
            }
        });

    }
}

//微信支付
async function wxPay(req, thisResponse) {
    //首先拿到前端传过来的参数
    let postData = req.body;
    let orderCode = postData.orderCode;
    let money = postData.money;
    let CODE = postData.code;

    let appid = wxConfig['wxMini' + postData.source].appId
    let appsecret = wxConfig['wxMini' + postData.source].secret
    let mchid = wxConfig['wxMini' + postData.source].mchid
    let mchkey = wxConfig['wxMini' + postData.source].mchkey

    let user = await userModel.user.findByPk(postData.uid)
    if (user.vipTime) {
        let returnData = {
            code: 0,
            msg: "已是会员，无需再次充值"
        }
        thisResponse.json(returnData)
    }  else {

        let url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + appsecret + '&js_code=' + CODE + '&grant_type=authorization_code'
        return request({ url: url, method: 'GET' }, async function (err, res, result11) {
            console.log("测试错误", result11)
            result11 = JSON.parse(result11);
            let openid;

            if (result11 && result11.openid) {
                openid = result11.openid
            }
            else {
                let thisUser = await userModel.user.findOne({
                    where: {
                        objectId: postData.uid
                    }
                })
                openid = thisUser.wcMiniId
            }

            //console.log('APP传过来的参数是', orderCode + '----' + money + '------'  + '----' + appid + '-----' + appsecret + '-----' + mchid + '-----' + mchkey);

            //首先生成签名sign
            // appid
            let mch_id = mchid;
            let nonce_str = wxMiniPayUnits.createNonceStr();
            let timestamp = wxMiniPayUnits.createTimeStamp();
            let body = '美术课件云助手-会员服务';
            let out_trade_no = orderCode;
            let total_fee = wxMiniPayUnits.getmoney(money);
            let spbill_create_ip = req.connection.remoteAddress; // 支持IPV4和IPV6两种格式的IP地址。调用微信支付API的机器IP
            let notify_url = wxurl;
            let trade_type = 'JSAPI';  // 'APP';公众号：'JSAPI'或'NATIVE'

            let sign = wxMiniPayUnits.paysignjsapi(appid, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, trade_type, mchkey);

            // console.log('sign==', sign);

            //组装xml数据
            var formData = "<xml>";
            formData += "<appid>" + appid + "</appid>";  //appid
            formData += "<body><![CDATA[" + "美术课件云助手-会员服务" + "]]></body>";
            formData += "<mch_id>" + mch_id + "</mch_id>";  //商户号
            formData += "<nonce_str>" + nonce_str + "</nonce_str>"; //随机字符串，不长于32位。
            formData += "<notify_url>" + notify_url + "</notify_url>";
            formData += "<openid>" + openid + "</openid>";
            formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>";
            formData += "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>";
            formData += "<total_fee>" + total_fee + "</total_fee>";
            formData += "<trade_type>" + trade_type + "</trade_type>";
            formData += "<sign>" + sign + "</sign>";
            formData += "</xml>";

            //console.log('formData===', formData);

            var url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

            request({ url: url, method: 'POST', body: formData }, function (err, response, body) {
                if (!err && response.statusCode == 200) {
                    console.log(body);

                    xmlreader.read(body.toString("utf-8"), async function (errors, response) {
                        if (null !== errors) {
                            console.log(errors)
                            return;
                        }
                        console.log('长度===', response.xml.prepay_id.text().length);
                        var prepay_id = response.xml.prepay_id.text();
                        console.log('解析后的prepay_id==', prepay_id);

                        //将预支付订单和其他信息一起签名后返回给前端
                        let package = "prepay_id=" + prepay_id;
                        let signType = "MD5";
                        let minisign = wxMiniPayUnits.paysignjsapimini(appid, nonce_str, package, signType, timestamp, mchkey);

                        //创建单据
                        await orderModel.order.create({
                            objectId: sid.uuid(),
                            out_trade_no: out_trade_no,
                            status: 0,
                            payMoney: Number(money),
                            storeMoney: (Number(money) * 0.8),
                            parent: postData.uid,
                            buyerId: postData.uid,
                            type: 2
                        })

                        const returnData = Common.clone(Constant.DEFAULT_SUCCESS);
                        returnData.data = {
                            'appId': appid,
                            'partnerId': mchid,
                            'prepayId': prepay_id,
                            'nonceStr': nonce_str,
                            'timeStamp': timestamp,
                            'package': 'Sign=WXPay',
                            'paySign': minisign,
                        }
                        thisResponse.json(returnData);
                    });
                }
            });
        })
    }
}

//获取session
async function getSession(req, response) {
    let postData = req.body;
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let appid = wxConfig['wxMini' + postData.source].appId
    let appsecret = wxConfig['wxMini' + postData.source].secret

    let APPID = appid;
    let SECRET = appsecret;
    let CODE = postData.code;
    let url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + APPID + '&secret=' + SECRET + '&js_code=' + CODE + '&grant_type=authorization_code'
    return request({ url: url, method: 'GET' }, async function (err, res, body) {
        body = JSON.parse(body);
        return body.openid
    })
}

